﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Apex.Common;
using Apex.Script.Models;
using Apex.Script.ViewModels;
using Microsoft.Maps.MapControl.WPF;
using Script.Components.Controls;

namespace Script.Components.Windows
{
    /// <summary>
    /// Interaction logic for CharactersWindow.xaml
    /// </summary>
    public partial class LocationsWindow : Elysium.Controls.Window
    {
        public ScriptViewModel ViewModel { get; private set; }

        public LocationsWindow(ScriptViewModel vm)
        {
            ViewModel = vm;
            InitializeComponent();
            lvLocations.DataContext = vm;
            StartProgress();
            cmbWeather.ItemsSource = Enum.GetValues(typeof(WeatherType));
            cmbTimeOfDay.ItemsSource = Enum.GetValues(typeof(TimeOfDay));
            cmbWeather.SelectedIndex = 0;
            cmbTimeOfDay.SelectedIndex = 0;
            List<TimeSpan> times = new List<TimeSpan>();
            for (int i = 0; i < 23; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    times.Add(new TimeSpan(i, j * 30, 0));
                }
            }
            cmbTime.ItemsSource = times;

            Task.Run(() =>
            {
                var curLoc = LocationServices.GetCurrentLocation();
                Dispatcher.Invoke(() =>
                    {
                        mpMap.Center = new Microsoft.Maps.MapControl.WPF.Location(curLoc.Lat, curLoc.Lon);
                        mpMap.ZoomLevel = 10;
                        StopProgress();
                    });
            });

            foreach (var x in vm.Locations)
            {
                CreateMarker(x);
            }

            vm.Locations.CollectionChanged += Locations_CollectionChanged;
        }

        private void CreateMarker(LocationViewModel x)
        {
            DynamicMapMarker marker = new DynamicMapMarker(x);
            MapLayer.SetPosition(marker, new Microsoft.Maps.MapControl.WPF.Location(x.Position.Lat, x.Position.Lon));
            MapLayer.SetPositionOrigin(marker, PositionOrigin.CenterLeft);
            mpMap.Children.Add(marker);
        }

        void Locations_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    foreach (LocationViewModel x in e.NewItems)
                    {
                        CreateMarker(x);
                    }
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    foreach (LocationViewModel x in e.OldItems)
                    {
                        foreach (var y in mpMap.Children)
                        {
                            if ((y as DynamicMapMarker).ViewModel == x)
                            {
                                mpMap.Children.Remove((y as DynamicMapMarker));
                                break;
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        #region Progress Helpers

        private void StartProgress()
        {
            blurEffect.Radius = 10;
            progressRing.Visibility = System.Windows.Visibility.Visible;
        }

        private void StopProgress()
        {
            blurEffect.Radius = 0;
            progressRing.Visibility = System.Windows.Visibility.Hidden;
        }

        #endregion

        #region Action bar

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            rectLiveIndicator.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            if (lvLocations.SelectedIndex < 0)
            {
                MessageBox.Show("Please select a location first.");
                return;
            }

           // why null? ViewModel.Locations.Remove(lvLocations.SelectedItem as LocationViewModel);
        }

        #endregion

        private void lvLocations_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var x = (lvLocations.SelectedItem as LocationViewModel);
            mpMap.ZoomLevel = 17;
            mpMap.Center = new Microsoft.Maps.MapControl.WPF.Location(x.Position.Lat, x.Position.Lon);
        }

        private void mpMap_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (rectLiveIndicator.Visibility == System.Windows.Visibility.Visible)
            {
                if (cmbTime.SelectedIndex < 0 || cmbTimeOfDay.SelectedIndex < 0 || cmbWeather.SelectedIndex < 0 || string.IsNullOrEmpty(tbName.Text))
                {
                    MessageBox.Show("Please fill all the data in the header of the map");
                    return;
                }

                e.Handled = true;
                Point mousePosition = e.GetPosition(this);
                mousePosition.Y -= 50;
                Microsoft.Maps.MapControl.WPF.Location pinLocation = mpMap.ViewportPointToLocation(mousePosition);

                Apex.Script.Models.Location l = new Apex.Script.Models.Location()
                {
                    ActualDate = (TimeSpan)cmbTime.SelectedItem,
                    Name = tbName.Text,
                    Position = new LatLon(pinLocation.Latitude, pinLocation.Longitude),
                    TimeOfDay = (TimeOfDay)cmbTimeOfDay.SelectedItem,
                    Weather = (WeatherType)cmbWeather.SelectedItem
                };

                ViewModel.Locations.Add(new LocationViewModel(l));
                rectLiveIndicator.Visibility = System.Windows.Visibility.Hidden;
            }
        }

    }
}
